package com.example.demo.dao.impl;


import com.example.demo.dao.ToupiaoDao;
import com.example.demo.model.Toupiao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Repository
@Transactional(rollbackFor = Exception.class)
public class ToupiaoDaoImpl  implements ToupiaoDao {

	@Autowired
	HibernateTemplate hibernateTemplate;


	@Override
	public void deleteBean(Toupiao bean) {
		hibernateTemplate.delete(bean);
		
	}

	@Override
	public void insertBean(Toupiao bean) {
		hibernateTemplate.save(bean);
		
	}

	@Override
	@SuppressWarnings("unchecked")
	public Toupiao selectBean(String where) {
		List<Toupiao> list = (List<Toupiao>) hibernateTemplate.find("from Toupiao " +where);
		if(list.size()==0){
			return null;
		}
		return list.get(0);
	}

	@Override
	public int selectBeanCount(String where) {
		long count = (Long)hibernateTemplate.find("select count(*) from Toupiao "+where).get(0);
		return (int)count;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Toupiao> selectBeanList(final int start,final int limit,final String where) {
		return (List<Toupiao>)hibernateTemplate.executeWithNativeSession((HibernateCallback) session -> {
			List<Toupiao> list = session.createQuery("from Toupiao "+where)
			.setFirstResult(start)
			.setMaxResults(limit)
			.list();
			return list;
		});
	}

	@Override
	public void updateBean(Toupiao bean) {
		hibernateTemplate.update(bean);
	}
	
	
}
